<?php
namespace app\admin\controller;

use think\Controller;
use app\service\ApiKeyService;

/**
 * API Key生成测试控制器
 */
class ApiKeyTest extends Controller
{
    /**
     * 生成测试API Key
     * 访问: http://your-domain/admin/api-key-test/generate
     */
    public function generate()
    {
        try {
            // 为客户生成API Key
            $createData = [
                'name' => '测试客户系统',
                'description' => '用于设备控制的测试API Key',
                'permissions' => ['device:command', 'device:query'],
                'ip_whitelist' => [], // 暂时不限制IP
                'expires_at' => date('Y-m-d H:i:s', strtotime('+1 year')) // 1年后过期
            ];

            // 添加详细的调试信息
            \think\facade\Log::info("API Key创建尝试: " . json_encode($createData));

            $result = ApiKeyService::createApiKey($createData);

            \think\facade\Log::info("API Key创建结果: " . json_encode($result));

            if ($result) {
                // 这就是我们要提供给客户的完整信息
                $clientInfo = [
                    'api_key' => $result['api_key'],        // 公开的API Key
                    'secret_key' => $result['secret_key'],  // 私密的签名密钥
                    'name' => $result['name'],
                    'expires_at' => $result['expires_at'],
                    'permissions' => ['device:command', 'device:query'],
                    'usage_instructions' => [
                        '1. 使用api_key作为Authorization头的值',
                        '2. 使用secret_key计算请求签名',
                        '3. 每次请求都需要包含时间戳和签名',
                        '4. 签名算法: HMAC-SHA256'
                    ]
                ];
                
                return json([
                    'code' => 1,
                    'message' => 'API Key生成成功',
                    'data' => $clientInfo
                ]);
            } else {
                return json(['code' => 0, 'message' => 'API Key生成失败']);
            }
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '生成失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 检查和创建数据库表
     * 访问: http://your-domain/admin/api-key-test/setup
     */
    public function setup()
    {
        try {
            // 检查数据库连接
            $db = \think\Db::connect('db_config2');

            // 检查api_keys表是否存在
            $apiKeysExists = $db->query("SHOW TABLES LIKE 'api_keys'");
            $apiLogsExists = $db->query("SHOW TABLES LIKE 'api_call_logs'");

            $result = [
                'database_connection' => 'OK',
                'api_keys_table' => !empty($apiKeysExists) ? 'EXISTS' : 'NOT_EXISTS',
                'api_call_logs_table' => !empty($apiLogsExists) ? 'EXISTS' : 'NOT_EXISTS'
            ];

            // 如果表不存在，创建表
            if (empty($apiKeysExists)) {
                $this->createApiKeysTable($db);
                $result['api_keys_table'] = 'CREATED';
            }

            if (empty($apiLogsExists)) {
                $this->createApiCallLogsTable($db);
                $result['api_call_logs_table'] = 'CREATED';
            }

            return json([
                'code' => 1,
                'message' => '数据库检查完成',
                'data' => $result
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '数据库检查失败: ' . $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * 创建api_keys表
     */
    private function createApiKeysTable($db)
    {
        $sql = "CREATE TABLE `api_keys` (
          `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
          `api_key` varchar(64) NOT NULL COMMENT 'API密钥',
          `secret_key` varchar(128) NOT NULL COMMENT '签名密钥',
          `name` varchar(100) NOT NULL COMMENT 'API Key名称',
          `description` text COMMENT '描述信息',
          `permissions` json COMMENT '权限列表',
          `ip_whitelist` json COMMENT 'IP白名单',
          `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：1=启用，0=禁用',
          `expires_at` datetime NOT NULL COMMENT '过期时间',
          `last_used_at` datetime DEFAULT NULL COMMENT '最后使用时间',
          `usage_count` int NOT NULL DEFAULT '0' COMMENT '使用次数',
          `created_at` datetime NOT NULL COMMENT '创建时间',
          `disabled_at` datetime DEFAULT NULL COMMENT '禁用时间',
          PRIMARY KEY (`id`),
          UNIQUE KEY `uk_api_key` (`api_key`),
          KEY `idx_status_expires` (`status`, `expires_at`),
          KEY `idx_created_at` (`created_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='API密钥管理表'";

        $db->execute($sql);

        // 插入测试数据
        $testData = [
            [
                'api_key' => 'ak_test_device_control_001',
                'secret_key' => 'sk_test_device_control_secret_key_001',
                'name' => '设备控制系统',
                'description' => '用于设备指令下发的API密钥',
                'permissions' => json_encode(['device:command', 'device:query']),
                'ip_whitelist' => json_encode([]), // 暂时不限制IP
                'status' => 1,
                'expires_at' => '2025-12-31 23:59:59',
                'created_at' => date('Y-m-d H:i:s'),
                'usage_count' => 0
            ]
        ];

        $db->name('api_keys')->insertAll($testData);
    }

    /**
     * 创建api_call_logs表
     */
    private function createApiCallLogsTable($db)
    {
        $sql = "CREATE TABLE `api_call_logs` (
          `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
          `api_key` varchar(64) NOT NULL COMMENT 'API密钥',
          `request_id` varchar(100) DEFAULT NULL COMMENT '请求ID',
          `method` varchar(10) NOT NULL COMMENT 'HTTP方法',
          `path` varchar(255) NOT NULL COMMENT '请求路径',
          `client_ip` varchar(45) NOT NULL COMMENT '客户端IP',
          `user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理',
          `request_body` text COMMENT '请求体',
          `response_code` int DEFAULT NULL COMMENT '响应状态码',
          `response_message` varchar(255) DEFAULT NULL COMMENT '响应消息',
          `execution_time` int DEFAULT NULL COMMENT '执行时间(毫秒)',
          `created_at` datetime NOT NULL COMMENT '创建时间',
          PRIMARY KEY (`id`),
          KEY `idx_api_key` (`api_key`),
          KEY `idx_created_at` (`created_at`),
          KEY `idx_request_id` (`request_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='API调用日志表'";

        $db->execute($sql);
    }

    /**
     * 查看API Key格式示例
     * 访问: http://your-domain/admin/api-key-test/format
     */
    public function format()
    {
        // 展示API Key的标准格式
        $example = [
            'api_key_format' => [
                'prefix' => 'ak_',
                'length' => '32位随机字符',
                'example' => 'ak_1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p'
            ],
            'secret_key_format' => [
                'prefix' => 'sk_',
                'length' => '64位随机字符', 
                'example' => 'sk_1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h'
            ],
            'complete_example' => [
                'api_key' => 'ak_test_device_control_001',
                'secret_key' => 'sk_test_device_control_secret_key_001',
                'name' => '客户系统名称',
                'permissions' => ['device:command', 'device:query'],
                'expires_at' => '2025-12-31 23:59:59'
            ]
        ];
        
        return json([
            'code' => 1,
            'message' => 'API Key格式说明',
            'data' => $example
        ]);
    }
}
